package com.southwind.springboottest.study.注解事件处理器;

/**
 * @description：TODO
 * @author： HXG
 * @create： 2023/12/18 17:51
 */
import java.awt.event.ActionListener;
import java.lang.reflect.*;
/**
 * Install action listener
 */
public class ActionListenerInstaller {
    public static void processAnnotations(Object obj) {
        try {
            Class cl = obj.getClass();
            for (Method m : cl.getDeclaredMethods()) {
                ActionListenerFor a = m.getAnnotation(ActionListenerFor.class);
                if (null != a) {
                    Field f = cl.getDeclaredField(a.source());
                    f.setAccessible(true);
                    addListener(f.get(obj), obj, m);
                    a.level();// 可以获取定义的level
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void addListener(Object source, final Object param, final
    Method m) throws NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                return m.invoke(param);
            }
        };
        Object listener = Proxy.newProxyInstance(null,
                new Class[]{java.awt.event.ActionListener.class},
                handler);
        Method adder = source.getClass().getMethod("addActionListener",
                ActionListener.class);
        adder.invoke(source, listener);
    }
}